<style lang="scss" scoped>
    .fileOperate{
        display: flex;
        align-items: center;
        button{
            margin-right: 20px;
        }
    }
    .uploadRemark{
        margin-top: 10px;
        color: #ccc;
    }
    .remarkPicture{
        margin-top: 10px;
        img{
            width: 100%
        }
    }
</style>

<template>
    <div>
        <header>
            <Upload :action="action" :accept="accept" :multiple="multiple" :before-upload="handleUploadFile">
                <div class="fileOperate">
                    <Button type="primary">选择文件</Button>
                    <div>
                        <a @click.stop="download">下载导入模板</a>
                    </div>
                </div>
            </Upload>
        </header>
        <div class="uploadRemark" v-html="uploadRemark"></div>
        <div class="remarkPicture">
            <img :src="picSrc" alt="">
        </div>
    </div>
</template>

<script>
import HttpService from "@/service/baseHttp";

export default {
    props: [
        "action",
        "accept",
        "data",
        "name",
        "multiple",
        "type",
        "easyMode",
        "beforeUpload",
        "formatter",
        "download",
        'warningtitle',
        "autoHandle",
        "picSrc",
        "uploadRemark",
    ],
    data() {
        return {
            fileList: [],
        }
    },
    methods: {
        handleUploadFile(file) {
            let flag = true;
            if (!flag) return false;
            let fileItem = {
                id: 0,
                name: file.name,
                file: file,
                percent: 0,
                status: 0,
                uploadStatus: 1
            }
            this.fileList.push(fileItem);
            this.upload()
            return false
        },
        async upload() {
            // 如果上传列表为空，则不执行任何操作
            if (!this.fileList || !this.fileList.length) return
            // 提交前验证
            if (this.beforeUpload && ! await this.beforeUpload(this.fileList)) return
            let promiseArr = this.fileList.map((item, index) => {
                item.uploadStatus = 1;
                item.percent = 0;
                return this.ajaxFile(index).then((res) => {
                    item.percent = 100;
                    // 是否需要自动处理多条（绝大多数情况不需要）
                    if (this.autoHandle) {
                        if (this.formatter) {
                            this.result = this.formatter(res, item)
                        }
                        else {
                            item.status = 2;
                            item.id = res.data.entity.id || null;
                            item.result = res.data;
                            this.result.opAt = item.result.entity.createdAt || null;
                            this.result.items.push({
                                attachId: item.result.entity.id || null,
                                attachOpAt: item.result.entity.createdAt || null,
                                attachTitle: item.result.entity.title || null,
                                attachBrief: item.result.entity.brief || null,
                                attachUrl: item.result.genUrl || null,
                                createdName:item.result.entity.createdName || null,
                                createdBy:item.result.entity.createdBy || null,
                                // filename: item.result.entity.filename
                            });
                            item.uploadStatus = 1;
                            this.result.originData.push(item.result);
                        }
                    }
                    else {
                        this.$Message.success(res.message);
                        this.$emit("on-success", res);
                        setTimeout(() => {
                            this.$emit('on-update');
                        }, 200);
                    }
                }, err => {
                    item.uploadStatus = 0;
                    // 上传失败更改文件状态
                    item.status = 3;
                    throw err;
                });
            });
            Promise.all(promiseArr).then(() => {
                this.$emit("on-success", this.result);
            }, err => {
                this.fileList = [];
                this.$Message.error({
                    content: err.message,
                    duration: 30,
                    closable: true
                });
            });
        },
        ajaxFile(index) {
            let url = this.action ? this.action: process.env.VUE_APP_APIURL_UC +"/api/v1/BizAttach/uploadFile";
            // 用原来的构造数据方式
            let formData = new FormData();
            Object.entries(this.data || {}).forEach(([key, val]) => {
                formData.append(key, val);
            });
            formData.append(this.name, this.fileList[index].file);
            formData.append("contextId", global.SYSID);
            let that = this;
            const args = [
                url,
                formData,
                {
                    headers: {
                        "Content-Type": "multipart/form-data",
                        Authorization: "Bearer " + global.AUTH_TOKEN,
                    },
                    withCredentials: true,
                    transformRequest(data) {
                        return data;
                    },
                    // 监听上传进度
                    onUploadProgress: function (progressEvent) {
                        that.fileList[index].status = 1;
                        that.fileList[index].percent =
                            (progressEvent.loaded / progressEvent.total) * 99;
                    },
                    // cancelToken: cancelXHR.token
                },
            ];
            // 发起请求
            const ajaxRequest = !this.action && typeof this.ajaxRequest === "function" ? this.ajaxRequest(...args.slice(1)) : HttpService.post(...args);
            return ajaxRequest;
        },
    }
}
</script>
